const fs = require("fs");
const path = require("path");
const cheerio = require("cheerio");
const XLSX = require("xlsx");

// =====================================================
// 分离中文与拼音
// =====================================================
function splitChineseAndPinyin(text) {
  if (!text || typeof text !== "string") {
    return { chinese: "", pinyin: "" };
  }

  const s = text.trim();

  // 按 code point 分割为真正的字符数组
  const chars = Array.from(s);

  const chineseRegex = /[\p{Script=Han}（）《》【】〈〉“”‘’。、·]/u;

  let lastIndex = -1;
  for (let i = 0; i < chars.length; i++) {
    if (chineseRegex.test(chars[i])) {
      lastIndex = i;
    }
  }

  if (lastIndex === -1) {
    return { chinese: "", pinyin: s };
  }

  const chinese = chars.slice(0, lastIndex + 1).join("").trim();
  const after = chars.slice(lastIndex + 1).join("").trim();

  const pinyinRegex = /^[\p{L}\d·ˉˊˇˋü: ]+$/u;

  if (pinyinRegex.test(after)) {
    return { chinese, pinyin: after };
  }

  return { chinese, pinyin: "" };
}



// =====================================================
// 判定是否为注解段
// =====================================================
function isNoteParagraph(text) {
  if (!text) return false;
  const s = text.trim();
  return s.startsWith("【注】") || s.startsWith("注");
}

// =====================================================
// 解析单个 HTML 文件
// =====================================================
function parseHtml(htmlContent) {
  const $ = cheerio.load(htmlContent);
  const elements = $("body").children().toArray(); // body下的所有直接子元素

  const entries = [];
  let current = null;
  let strongIndex = 0; // 用于记录当前 strong 是第几个

  for (const el of elements) {
    const $el = $(el);
    const tagName = el.tagName.toLowerCase();
    const text = $el.text().trim();
    if (!text) continue;

    if (tagName === "p") {
      const hasStrong = $el.find("strong").length > 0;

      if (hasStrong) {
        strongIndex++;

        if (strongIndex % 2 === 1) {
          // 第 1 个 strong（或每对 strong 的第 1 个） → 中文词目
          if (current) entries.push(current); // 保存上一条目
          const { chinese, pinyin } = splitChineseAndPinyin(text);
          current = { chinese, pinyin, zhDesc: "", enWord: "", enDesc: "", note: "" };
        } else {
          // 第 2 个 strong（或每对 strong 的第 2 个） → 英文词目
          if (!current) {
            current = { chinese: "", pinyin: "", zhDesc: "", enWord: "", enDesc: "", note: "" };
          }
          current.enWord = text;
        }
      } else {
        // 普通 p 段落
        if (!current) {
          current = { chinese: "", pinyin: "", zhDesc: "", enWord: "", enDesc: "", note: "" };
        }

        if (isNoteParagraph(text)) {
          current.note += (current.note ? "\n" : "") + text;
        } else if (current.enWord) {
          current.enDesc += (current.enDesc ? "\n" : "") + text;
        } else {
          current.zhDesc += (current.zhDesc ? "\n" : "") + text;
        }
      }
    } else if (tagName === "ul" || tagName === "ol") {
      // 列表内容加入描述
      if (!current) {
        current = { chinese: "", pinyin: "", zhDesc: "", enWord: "", enDesc: "", note: "" };
      }
      const listText = $el.text().trim();
      if (current.enWord) {
        current.enDesc += (current.enDesc ? "\n" : "") + listText;
      } else {
        current.zhDesc += (current.zhDesc ? "\n" : "") + listText;
      }
    } else {
      // 其他标签可按需处理或忽略
      continue;
    }
  }

  // 循环结束，把最后一条条目加入结果
  if (current) entries.push(current);

  return entries;
}




// =====================================================
// 批量处理 HTML 文件，生成 Excel
// =====================================================
function run(f) {
  const folder = f;

  const files = fs.readdirSync(folder)
    .filter(f => f.toLowerCase().endsWith(".html"))
    .sort((a, b) => {
      const numA = parseInt(a.split('.')[0], 10);
      const numB = parseInt(b.split('.')[0], 10);
      if (isNaN(numA) && isNaN(numB)) return 0;
      if (isNaN(numA)) return 1;
      if (isNaN(numB)) return -1;
      return numA - numB;
    });

  const excelData = [];

  for (const file of files) {
    const fullPath = path.join(folder, file);
    const html = fs.readFileSync(fullPath, "utf-8");

    const records = parseHtml(html);
    const docxName = file.replace(/\.html?$/i, ".docx");
    for (const r of records) {
        console.log(r);
        
      excelData.push({
        filename: docxName,
        chinese: r.chinese,
        pinyin: r.pinyin,
        zh_note: r.zhDesc,
        en_word: r.enWord,
        en_note: r.enDesc,
        note: r.note
      });
    }
  }

  const wb = XLSX.utils.book_new();
  const ws = XLSX.utils.json_to_sheet(excelData, {
    header: ["filename", "chinese", "pinyin", "zh_note", "en_word", "en_note", "note"]
  });
  XLSX.utils.book_append_sheet(wb, ws, "data");
  XLSX.writeFile(wb, "result.xlsx");

  console.log("解析完成 → 已生成 result.xlsx");
}

run("./htmls");
